package org.lex.ftp.net;

import org.lex.ftp.ui.explorer.FTPExplorerUtils;
import org.lex.net.ftp.IFTPClient;
import org.lex.net.ftp.IFTPFile;
import org.lex.utils.Pair;
import org.lex.utils.pool.DaemonExecutor;
import org.lex.utils.text.SizeFormat;


public class FTPUtils {
	/**
	 * @param files
	 * @return (file count, total file size)
	 */
	public static Pair<Integer, Long> getFileStatistics(IFTPFile[] files) {
		if (null == files)
			files = FTPExplorerUtils.EMPTY;
		int fileCount = 0;
		long size = 0L;
		for (int i = 0; i < files.length; i++) {
			IFTPFile file = files[i];
			if (file.isFile()) {
				fileCount++;
				size += file.getSize();
			}
		}
		return new Pair<Integer, Long>(fileCount, size);
	}

	public static Pair<String, String> generateFileStatistics(IFTPFile[] files) {
		if (null == files)
			files = FTPExplorerUtils.EMPTY;
		Pair<Integer, Long> p = getFileStatistics(files);
		StringBuilder buf = new StringBuilder();
		buf.append(files.length).append(" objects ( ");
		buf.append(p.first()).append(" files, ");
		buf.append(files.length - p.first()).append(" folders ) ");
		String info = buf.toString();
		buf.setLength(0);
		buf.append(SizeFormat.autoFormat(p.second())).append('B');
		return new Pair<String, String>(info, buf.toString());
	}

	public static void close(final IFTPClient ftp) {
		if (null == ftp)
			return;
		DaemonExecutor.execute(new Runnable() {
			public void run() {
				try {
					ftp.quit();
				} catch (Exception e) {
				}
				while (true == ftp.isServerOpen()) {
					try {
						ftp.closeServer();
					} catch (Exception e) {
					}
					try {
						Thread.sleep(500);
					} catch (Exception e) {
					}
				}
			}
		});
	}
}
